package com.chushouya.manager.service.admin.impl;

import com.chushouya.common.constant.MenuSystemTypeEnum;
import com.chushouya.manager.service.admin.AdminUserService;
import com.chushouya.manager.service.admin.MenuService;
import com.chushouya.manager.service.admin.PermissionService;
import com.chushouya.manager.service.admin.RoleService;
import com.general.framework.core.lang.Jsons;
import com.general.framework.data.redis.RedisCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

@Service
@Slf4j
public class PermissionServiceImpl implements PermissionService {

    @Resource
    private RoleService roleService;

    @Resource
    private MenuService menuService;

    @Resource
    private AdminUserService adminUserService;

    @Resource
    private RedisCache redisCache;


    @PostConstruct
    public void initSystemPermCache() {
        //this.initPermCache(MenuSystemTypeEnum.ADMIN_SYSTEM, Constants.ADMIN_MENU_PERM_CACHE);
        //this.initPermCache(MenuSystemTypeEnum.MERCHANT_SYSTEM, Constants.MERCHANT_MENU_PERM_CACHE);
    }

    private void initPermCache(MenuSystemTypeEnum systemType, String menuPermCacheKey) {
        Map<String, String> permMap = menuService.getButtonPermissions(systemType.value());
        log.info("====init {}功能权限 start", systemType.named());
        log.info("====permMap:{}", Jsons.toJsonString(permMap));
        redisCache.deleteObject(menuPermCacheKey);
        if (permMap.size() > 0) {
            final Map<String, String> sortedMap = this.sortByKey(permMap);
            sortedMap.keySet().forEach(permission ->{
                String mKey = permission.replaceAll("//", "/");
                redisCache.setCacheMapValue(menuPermCacheKey, mKey, sortedMap.get(permission));
            });
        }
        log.info("====init {}功能权限 success", systemType.named());
    }

    private Map<String, String> sortByKey(Map<String, String> map) {
        Map<String, String> result = new LinkedHashMap<>(map.size());
        map.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
        return result;
    }
    @Override
    public Set<String> getRoles(Long adminUserId) {
        Set<String> roles = new HashSet<>();
        // 管理员拥有所有权限
        if (adminUserService.isSuperAdmin(adminUserId)) {
            roles.add("admin");
        } else {
            roles.addAll(roleService.selectRolePermission(adminUserId));
        }
        return roles;
    }
    @Override
    public Set<String> getAdminPermission(Long adminUserId) {
        Set<String> perms = new HashSet<>();
        // 管理员拥有所有权限
        if (adminUserService.isSuperAdmin(adminUserId)) {
            perms.add("*:*:*");
        } else {
            perms.addAll(menuService.selectAdminPerms(adminUserId));
        }
        return perms;
    }

    @Override
    public Set<String> getMerchantPermission(Boolean isMaster, Long adminUserId) {
        Set<String> perms = new HashSet<>();
        if (isMaster) {
            perms.addAll(menuService.selectAllMerchantPerms());
        } else {
            perms.addAll(menuService.selectMerchantPerms(adminUserId));
        }
        return perms;
    }
}
